<script setup lang="ts">
import html2canvas from 'html2canvas'
import directionNorthImg from '@/assets/image/common/directionNorth.png'
import { removeTempMapFactor, saveMapPic } from '@/utils'
import { ElLoading, ElMessage } from 'element-plus'
import { loadLayerMarkerInfo } from './RightLayerManager.module'
const firefightPlotStore = useFirefightPlotStore()

const currentCheckLayerList: any = computed(() => {
  return firefightPlotStore.currentCheckLayerList
})

const userInfo: any = computed(() => {
  return JSON.parse(localStorage.getItem('userXfjgJyryInfo') || '{}') || ''
})

const plotName = ref('')
const plotTime = ref('')
const imgUrl = ref()
const plotScaleWidth = ref('')
const plotScaleText = ref('')
let loading: any
const getCurrentTime = () => {
  const time = new Date()
  const timeList = time.toLocaleString().split(' ')
  const dateTime = timeList[0].split('/')
  const hourList = timeList[1].split(':')
  const year = parseInt(dateTime[0])
  const month = parseInt(dateTime[1])
  const day = parseInt(dateTime[2])
  return year + '年' + month + '月' + day + '日 ' + hourList[0] + ':' + hourList[1]
}
/**
 * 1. 切换视角,
 * 2. 遍历选中图层, 将图层序号 存入 store 中,查询选中图层标绘数据并上图,
 * 3. 将该视角下图片导出, 放入导出图中进行下一步操作
 * 4. 将导出图 转成图片并保存到接口中
 * 5. 将上图数据删除。
 **/
watch(
  () => firefightPlotStore.exportLayerFlag,
  async (newV) => {
    if (newV) {
      if (currentCheckLayerList.value.length) {
        // 添加遮罩
        loading = ElLoading.service({
          lock: true,
          text: '导出中...',
          background: 'rgba(0, 0, 0, 1)',
        })
        // 切换视角
        resetViewAngle()
        // 获取 比例尺数据
        getPlotScaleData()
        // 移除已经加载的标绘要素
        currentCheckLayerList.value.forEach((item: any) => {
          removeTempMapFactor(item.id)
        })
        // 开始遍历选中标绘图 并导出
        await traverseLayerList(currentCheckLayerList.value.length)
      }
    }
  }
)

async function traverseLayerList(len: number) {
  const length = currentCheckLayerList.value.length
  if (length) {
    for (let i = 0; i < length; i++) {
      // 加载当前图层标绘数据
      await setLoadMapMarkerPromise(currentCheckLayerList.value[i], i)
      // 设置导出图数据：图片、标题、时间
      await setExportPlotData(currentCheckLayerList.value[i])
      // 将导出图dom 转成 canvas 并生成图片 上传到接口中
      await transformHTML2CanvasPic(i)
      // 移除当前图层上图要素
      await removeTempMapFactor(currentCheckLayerList.value[i].id)
    }
    setTimeout(() => {
      firefightPlotStore.exportLayerFlag = false
      loading?.close()
      ElMessage({
        type: 'success',
        message: '导出成功',
      })
    }, 2000)
  }
}

async function setLoadMapMarkerPromise(data: any, index: number) {
  return await new Promise<void>(async (resolve, reject) => {
    await loadLayerMarkerInfo(data)
    resolve()
  })
}
function setExportPlotData(item: any) {
  return new Promise<void>(async (resolve, reject) => {
    // 修改导出图 图片 名称和 时间
    imgUrl.value = await saveMapPic()
    plotName.value = item?.bhtmc
    plotTime.value = getCurrentTime()
    resolve()
  })
}

const param = new FormData()
async function transformHTML2CanvasPic(index: number) {
  new Promise<void>(async (resolve, reject) => {
    const dom = document.getElementById('fireFightExportPlot')
    if (!dom) {
      return
    }
    await html2canvas(dom, { useCORS: true }).then(async (canvas: any) => {
      const img = await canvas.toDataURL('image/jpeg', 0.9)
      const content = encodeURI(img)
      function b64toBlob(dataURI: string) {
        const byteString = atob(dataURI.split(',')[1])
        const ab = new ArrayBuffer(byteString.length)
        const ia = new Uint8Array(ab)
        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i)
        }
        return new Blob([ab], { type: 'image/png' })
      }

      const param = new FormData()
      param.append('fjmc', `${currentCheckLayerList.value[index].bhtmc}.png`)
      param.append('ssid', currentCheckLayerList.value[index].id)
      param.append('qyid', (useChemicalStore().qyInfo as any).id)
      param.append('multipartFile', b64toBlob(content))

      insertUpdatePlotFile(param).then((res: any) => {
        imgUrl.value = ''
        console.log('导出标绘图', res)
      })
      resolve()
    })
  })
}

function getPlotScaleData() {
  const scaleBarDom: any = document.getElementsByClassName('distance-legend-scale-bar')[0]
  const scaleTextDom: any = document.getElementsByClassName('distance-legend-label')[0]
  if (scaleBarDom) {
    plotScaleWidth.value = scaleBarDom?.style.width || '66px'
  }

  if (scaleTextDom) {
    plotScaleText.value = scaleTextDom.innerHTML || '10m'
  }
}

/** 切换视角 TODO */
function resetViewAngle() {
  const chemicalStore = useChemicalStore()
  // 复位操作 初始化模型视角（正俯视角）、位置（企业中心点）、方向（指北）、层级
  window.GCamera.flyTo({
    pos: {
      lng: chemicalStore.tileSetOptions.tx,
      lat: chemicalStore.tileSetOptions.ty,
      height: 1200,
    },
  })
}
</script>
<template>
  <div id="fireFightExportPlot" class="fireFightExportPlot-container">
    <!-- 头部 -->
    <div class="header">{{ plotName }}</div>

    <img :src="directionNorthImg" class="w-46px h-46px absolute right-35px top-41px" />
    <div class="fireFightExportPlot-main">
      <img style="border: 4px solid #000" :src="imgUrl" class="w-1671px h-943px" />
    </div>

    <div class="fireFightExportPlot-bottom">
      <div class="length-group">
        <div class="length" :style="{ width: plotScaleWidth }"></div>
        <div style="margin: -2px 0 0 10px">{{ plotScaleText }}</div>
      </div>
      <div>制图单位 : {{ userInfo?.sjjgmc }}</div>
      <div>制图人 : {{ userInfo?.xm }}</div>
      <div>制图时间 : {{ plotTime }}</div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.fireFightExportPlot {
}
.fireFightExportPlot-container {
  position: absolute;
  left: 20px;
  top: 20px;
  width: 1920px;
  height: 1079px;
  z-index: -1;
  background: #ffffff;
  border: 1px solid #666666;

  .header {
    width: 100%;
    height: 86px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36px;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: #000000;
  }
  .fireFightExportPlot-main {
    width: 1700px;
    height: 971px;
    margin: 71px 0 0 110px;
    border: 4px solid #000;
    padding: 6px;
    box-sizing: border-box;
  }
  .fireFightExportPlot-bottom {
    width: 1700px;
    display: flex;
    justify-content: space-between;
    margin: 5px 0 0 110px;
    font-size: 20px;
    font-family: Microsoft YaHei;
    font-weight: bold;
    color: #000000;
    .length-group {
      display: flex;
      margin-top: 5px;
      .length {
        width: 66px;
        height: 16px;
        border: 4px solid #000;
        border-top: none;
      }
    }
  }
}
</style>
